﻿// Decompiled with JetBrains decompiler
// Type: Commom.Util.Xml
// Assembly: MT5Trade, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 8045A2CB-DBD6-41AD-8804-F98CAC1BDC8D
// Assembly location: C:\projects\trade\trade_tool\trade0812\MT5Trade.dll

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

#nullable enable
namespace Commom.Util;

public class Xml
{
  public Xml(string xml = null)
  {
    this.Document = new XmlDocument();
    this.Document.LoadXml(this.GetXml(xml));
    this.Root = this.Document.DocumentElement;
    if (this.Root == null)
      throw new ArgumentException(nameof (xml));
  }

  private string GetXml(string xml) => !string.IsNullOrWhiteSpace(xml) ? xml : "<xml></xml>";

  public XmlDocument Document { get; }

  public XmlElement Root { get; }

  public XmlNode AddNode(string name, object value = null, XmlNode parent = null)
  {
    XmlNode node = this.CreateNode(name, value, XmlNodeType.Element);
    this.GetParent(parent).AppendChild(node);
    return node;
  }

  private XmlNode CreateNode(string name, object value, XmlNodeType type)
  {
    XmlNode node = this.Document.CreateNode(type, name, string.Empty);
    if (!string.IsNullOrWhiteSpace(value.SafeString()))
      node.InnerText = value.SafeString();
    return node;
  }

  private XmlNode GetParent(XmlNode parent) => parent == null ? (XmlNode) this.Root : parent;

  public XmlNode AddCDataNode(object value, XmlNode parent = null)
  {
    XmlNode node = this.CreateNode(IdUtil.GuidNoSpilt(), value, XmlNodeType.CDATA);
    this.GetParent(parent).AppendChild(node);
    return node;
  }

  public XmlNode AddCDataNode(object value, string parentName)
  {
    XmlNode node = this.CreateNode(parentName, (object) null, XmlNodeType.Element);
    this.Root.AppendChild(node);
    return this.AddCDataNode(value, node);
  }

  public override string ToString() => this.Document.OuterXml;

  public static XDocument ToDocument(string xml) => XDocument.Parse(xml);

  public static List<XElement> ToElements(string xml)
  {
    XDocument document = Commom.Util.Xml.ToDocument(xml);
    return document?.Root == null ? new List<XElement>() : document.Root.Elements().ToList<XElement>();
  }
}
